import { Component } from 'react';

import { Button, Card, Form, Input, Checkbox, message } from 'antd';

import logo from 'assets/logo.png';

import { login } from 'api/user';

import { setToken } from 'utils/storage';

import styles from './index.module.scss';
export default class Login extends Component {
  // 登录请求接口
  onFinish = async (values) => {
    try {
      const res = await login(values);
      // 存储token
      // localStorage.setItem('geek_pc', res.data.token);
      setToken(res.data.token);
      // 跳转到首页
      this.props.history.push('/');
      message.success('登录成功', 1);
    } catch (err) {
      if (err.response) {
        message.warning(err.response.data.message, 1);
      }
    }
  };
  render() {
    return (
      <div className={styles.login}>
        <Card className="login-container">
          <img className="login-logo" src={logo} alt="" />
          {/* 表单 */}
          <Form
            size="large"
            validateTrigger={['onChange', 'onBlur']}
            onFinish={this.onFinish}
            initialValues={{
              agree: true,
              mobile: '13911111111',
              code: '246810',
            }}
          >
            <Form.Item
              name="mobile"
              rules={[
                { required: true, message: '手机号不能为空' },
                { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式错误' },
              ]}
            >
              <Input placeholder="请输入手机号" />
            </Form.Item>

            <Form.Item
              name="code"
              rules={[
                { required: true, message: '验证码不能为空' },
                { pattern: /^\d{6}$/, message: '验证格式错误' },
              ]}
            >
              <Input placeholder="请输入验证码" />
            </Form.Item>

            <Form.Item
              name="agree"
              valuePropName="checked"
              rules={[
                {
                  validator: (_, value) =>
                    value === true
                      ? Promise.resolve()
                      : Promise.reject('请阅读并同意用户协议'),
                },
              ]}
            >
              <Checkbox>我已阅读并同意[用户协议]和[隐私条款]</Checkbox>
            </Form.Item>

            <Form.Item>
              <Button type="primary" htmlType="submit" block>
                登录
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    );
  }
}
